﻿using System;
using System.Collections.Generic;
using System.Text;
using System.AddIn;
using System.AddIn.Pipeline;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Globalization;
using Toolbox.Plugin.Interfaces;
using System.ComponentModel.Composition;
using System.Threading;

namespace Toolbox.Plugin.FileHandler
{
    [PluginDescription("Local File Handler"), PluginAdressable("file")]
    public class LocalFileHandler : FileHandler, IPluginFileHandler
    {
        public string[] List()
        {
            List<string> l = new List<string>();
            FileInfo fi = new FileInfo(this.Directory.LocalPath);

            if (fi.Directory.Exists)
            {
                FileInfo[] files = fi.Directory.GetFiles(fi.Name, SearchOption.TopDirectoryOnly);

                if (files.Length > 0)
                {
                    FileHandler.GetDatePartition<FileInfo>(ref files, this.BatchSize > 0 ? this.BatchSize : files.Length, FileHandler.GetFileInfoDate, this.CurrentDate);
                }

                foreach (FileInfo f in files)
                {
                    l.Add(f.Name);
                    this.CurrentDate = f.LastWriteTime;
                }
            }

            return l.ToArray();
        }

        public void Get(ref string[] files)
        {
            for (int i = 0; i < files.Length; i++)
            {
                this.Get(ref files[i]);
            }
        }

        public void Get(ref string file)
        {
            FileInfo remote = new FileInfo(this.Directory.LocalPath + "\\" + file);
            FileInfo local = new FileInfo(Path.GetTempPath() + "\\" + remote.Name);

            while (IsFileLocked(remote))
            {
                Thread.Sleep(10000);
            }

            file = local.FullName;

            File.Copy(remote.FullName, file, true);
            File.SetCreationTime(file, remote.CreationTime);
        }

        public void Put(string[] files)
        {
            for (int i = 0; i < files.Length; i++)
            {
                this.Put(files[i]);
            }
        }

        public void Put(string file)
        {
            FileInfo local = new FileInfo(file);
            FileInfo remote = new FileInfo(this.Directory.LocalPath + "\\" + local.Name);

            while (IsFileLocked(remote))
            {
                Thread.Sleep(10000);
            }

            file = remote.FullName;

            File.Copy(local.FullName, file, true);
            File.SetCreationTime(file, local.CreationTime);
        }
    }
}
